#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <functional>
#include <memory>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_n
{
    // 父类提供接口，子类实现接口
    const static int gsockfd = -1;
    const static int gbacklog = 8;
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };
    class Socket;
    using SockPtr = std::shared_ptr<Socket>; // 父类中也用到了，所以在父类前面声明
    class Socket
    {
    public:
        virtual void CreatSocket() = 0;
        virtual void BindSocket(uint16_t port) = 0;
        virtual void SetListenStatus(int balcklog = gbacklog) = 0;
        virtual SockPtr Accept(InetAddr &client_addr) = 0;
        virtual bool Connect(const std::string &sever_ip, uint16_t sever_port) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;
        virtual ssize_t Recv(std::string &out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;
        // 创建监听套接字
        void CreatListenSocket(uint16_t port)
        {
            CreatSocket();
            BindSocket(port);
            SetListenStatus();
        }
        // 客户端套接字
        bool CreatClientSocket(const std::string &sever_ip, uint16_t sever_port)
        {
            CreatSocket();
            return Connect(sever_ip, sever_port);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = gsockfd)
            : _sockfd(sockfd)
        {
        }
        TcpSocket(TcpSocket &socket)
            : _sockfd(socket._sockfd)
        {
        }
        void CreatSocket() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket creat error\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket creat success,sockfd: %d\n", _sockfd);
        }
        void BindSocket(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success\n");
        }
        void SetListenStatus(int balcklog) override
        {
            if (listen(_sockfd, balcklog) < 0)
            {
                LOG(FATAL, "set listen error\n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success\n");
        }
        SockPtr Accept(InetAddr &client_addr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return nullptr; // 返回一个用nullptr构造的智能指针
            }
            client_addr = InetAddr(client);
            LOG(INFO, "get a new link, client info: %s\n", client_addr.AddrStr().c_str());

            return std::make_shared<TcpSocket>(sockfd); // C++14
        }
        bool Connect(const std::string &sever_ip, uint16_t sever_port) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(sever_port);
            ::inet_pton(AF_INET, sever_ip.c_str(), &server.sin_addr);

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                return false;
            }
            return true;
        }
        int Sockfd() override
        {
            return _sockfd;
        }
        void Close() override
        {
            if (_sockfd > 0)
                close(_sockfd);
        }
        ssize_t Recv(std::string &out) override
        {
            char inbuffer[1024];
            ssize_t n = recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                out = inbuffer;
            }
            return n;
        }
        ssize_t Send(const std::string &in) override
        {
            return send(_sockfd, in.c_str(), in.size(), 0);
        }

    private:
        int _sockfd;
    };
}